<template>
	<view class="accounting-container">
		<!-- 顶部导航栏 -->
		<u-navbar bgColor="#F5F9FC" :placeholder="true">
			<view slot="left" class="navigate-title">
				<navigator url="/pages/index/index" open-type="switchTab" class="back-button">
					<view style="display: flex; align-items: center;">
						<u-icon color="#1e88e5" name="arrow-left"></u-icon>
						<text class="header-title">记账管理</text>
					</view>
				</navigator>
			</view>
		</u-navbar>

		<!-- 筛选按钮 -->
		<view class="filter-button-container">
			<view class="header-right-section">
				<view class="filter-button" @click="toggleFilterPanel">
					<u-icon name="list-dot" color="#52aa7d" size="24"></u-icon>
				</view>
			</view>
		</view>

		<!-- 筛选面板 -->
		<view class="filter-panel" v-if="showFilterPanel">
			<!-- 固定顶部按钮区域：取消（左上）、重置（居中）、确定（右上） -->
			<view class="filter-actions-top">
				<view class="cancel-button" @click="showFilterPanel = false">取消</view>
				<view class="reset-button" @click="resetFilter">重置筛选条件</view>
				<view class="apply-button" @click="applyFilter">确定</view>
			</view>
			<view class="panel">
				<view class="filter-content">
					<view class="filter-section">
						<text class="filter-label">日期范围</text>
						<view class="date-range-picker">
							<picker mode="date" class="date-picker" @change="onStartDateChange" :value="startDate">
								<view class="picker-content">{{ startDate || '开始日期' }}</view>
							</picker>
							<text class="date-separator">至</text>
							<picker mode="date" class="date-picker" @change="onEndDateChange" :value="endDate">
								<view class="picker-content">{{ endDate || '结束日期' }}</view>
							</picker>
						</view>
					</view>

					<view class="filter-section">
						<text class="filter-label">记录类型</text>
						<picker class="type-picker" @change="onRecordTypeChange" :value="selectedRecordType"
							:range="recordTypes" :range-key="'label'">
							<view class="picker-content">{{ recordTypes[selectedRecordType].label }}</view>
						</picker>
					</view>

					<view class="filter-section">
						<text class="filter-label">收入类型</text>
						<picker class="income-picker" @change="onIncomeCategoryChange" :value="selectedIncomeCategory"
							:range="incomeCategories" :range-key="'label'">
							<view class="picker-content">{{ incomeCategories[selectedIncomeCategory].label }}</view>
						</picker>
					</view>

					<view class="filter-section">
						<text class="filter-label">支出类型</text>
						<picker class="expense-picker" @change="onExpenseCategoryChange"
							:value="selectedExpenseCategory" :range="expenseCategories" :range-key="'label'">
							<view class="picker-content">{{ expenseCategories[selectedExpenseCategory].label }}</view>
						</picker>
					</view>

					<!-- 布尔类型筛选：u-radio-group 横向排列（无边框） -->
					<view class="filter-section boolean-filter">
						<text class="filter-label">是否关联发票</text>
						<u-radio-group v-model="selectedHasInvoice" placement="row"
							@change="handleBooleanChange('hasInvoice', $event)">
							<u-radio :name="0" :customStyle="{ flex: 1, textAlign: 'center' }">全部</u-radio>
							<u-radio :name="1" :customStyle="{ flex: 1, textAlign: 'center' }">是</u-radio>
							<u-radio :name="2" :customStyle="{ flex: 1, textAlign: 'center' }">否</u-radio>
						</u-radio-group>
					</view>

					<view class="filter-section boolean-filter">
						<text class="filter-label">是否关联银行流水</text>
						<u-radio-group v-model="selectedHasBankFlow" placement="row"
							@change="handleBooleanChange('hasBankFlow', $event)">
							<u-radio :name="0" :customStyle="{ flex: 1, textAlign: 'center' }">全部</u-radio>
							<u-radio :name="1" :customStyle="{ flex: 1, textAlign: 'center' }">是</u-radio>
							<u-radio :name="2" :customStyle="{ flex: 1, textAlign: 'center' }">否</u-radio>
						</u-radio-group>
					</view>

					<view class="filter-section boolean-filter">
						<text class="filter-label">是否生成记账凭证</text>
						<u-radio-group v-model="selectedHasVoucher" placement="row"
							@change="handleBooleanChange('hasVoucher', $event)">
							<u-radio :name="0" :customStyle="{ flex: 1, textAlign: 'center' }">全部</u-radio>
							<u-radio :name="1" :customStyle="{ flex: 1, textAlign: 'center' }">是</u-radio>
							<u-radio :name="2" :customStyle="{ flex: 1, textAlign: 'center' }">否</u-radio>
						</u-radio-group>
					</view>

					<view class="filter-section boolean-filter">
						<text class="filter-label">是否有附件</text>
						<u-radio-group v-model="selectedHasAttachment" placement="row"
							@change="handleBooleanChange('hasAttachment', $event)">
							<u-radio :name="0" :customStyle="{ flex: 1, textAlign: 'center' }">全部</u-radio>
							<u-radio :name="1" :customStyle="{ flex: 1, textAlign: 'center' }">是</u-radio>
							<u-radio :name="2" :customStyle="{ flex: 1, textAlign: 'center' }">否</u-radio>
						</u-radio-group>
					</view>
				</view>
			</view>
		</view>

		<!-- 统计卡片 -->
		<view class="stats-container">
			<view class="stat-card income-card">
				<text class="stat-label">总收入</text>
				<text class="stat-value">¥{{ formatCurrency(totalIncome) }}</text>
			</view>
			<view class="stat-card expense-card">
				<text class="stat-label">总支出</text>
				<text class="stat-value">¥{{ formatCurrency(totalExpense) }}</text>
			</view>
		</view>

		<!-- 支出分类展示 -->
		<view class="expense-category-container">
			<view class="category-header">
				<text class="category-title">支出分类</text>
				<view class="category-actions">
					<text class="compare-text">对比上月</text>
					<u-switch v-model="compareWithLastMonth" size="24"></u-switch>
				</view>
			</view>
			<view class="category-list">
				<view class="category-item" v-for="(item, index) in displayedCategories" :key="index">
					<view class="category-info">
						<text class="category-rank">{{ index + 1 }}.</text>
						<text class="category-name">{{ item.categoryName }}</text>
						<text class="category-percentage">{{ item.percentage }}</text>
					</view>
					<text class="category-amount">{{ item.amount }}</text>
				</view>
			</view>
			<view class="expand-all" @click="toggleExpandAll">
				<text>{{ showAllCategories ? '收起' : '展开全部' }}</text>
				<u-icon :name="showAllCategories ? 'arrow-up' : 'arrow-down'" size="18" color="#666"></u-icon>
			</view>
		</view>

		<!-- 记账记录列表 -->
		<view class="records-container" v-if="accountingRecords.length > 0">
			<view class="records-header">
				<text class="records-title">记账记录</text>
			</view>
			<view class="records-list">
				<view class="record-card" v-for="record in accountingRecords" :key="record.id">
					<view class="record-icon" :class="record.type === 'income' ? 'income-icon' : 'expense-icon'">
						<u-icon :name="record.type === 'income' ? 'plus-circle' : 'minus-circle'"
							:color="record.type === 'income' ? '#10B981' : '#EF4444'" size="24"></u-icon>
					</view>
					<view class="record-details">
						<view class="record-category" style="display: flex;justify-content: space-between;">
							<view>{{ record.categoryLabel }}</view>
							<view class="record-amount"
								:class="record.type === 'income' ? 'income-amount' : 'expense-amount'">
								{{ record.type === 'income' ? '+' : '-' }}¥{{ formatCurrency(record.amount) }}
							</view>
						</view>
						<text class="record-date">{{ record.date }}</text>

						<!-- 发票、银行水号、附件信息 -->
						<view class="record-additional-info">
							<view class="info-item">
								<text class="info-label">发票：</text>
								<text class="info-value">{{ record.hasInvoice ? '有' : '无' }}</text>
							</view>
							<view class="info-item">
								<text class="info-label">银行水号：</text>
								<text class="info-value"
									style="white-space: nowrap;">{{ record.bankSerial || '无' }}</text>
							</view>
							<view class="info-item">
								<text class="info-label">记账凭证：</text>
								<text class="info-value">{{ record.hasVoucher ? '有' : '无' }}</text>
							</view>
							<view class="info-item">
								<text class="info-label">附件：</text>
								<text class="info-value">{{ record.hasAttachment ? '有' : '无' }}</text>
							</view>
						</view>

						<!-- 编辑/删除按钮区域 -->
						<view class="record-actions-row">
							<view class="record-actions">
								<navigator class="edit-button" :url="'/pageNew/pages/accounting/edit?id=' + record.id">
									<u-icon name="edit-pen" color="#374151" size="20"></u-icon>
								</navigator>
								<view class="delete-button" @click="confirmDelete(record.id)">
									<u-icon name="trash" color="#EF4444" size="20"></u-icon>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
		</view>

		<!-- 空状态 -->
		<view class="empty-state" v-else>
			<u-empty text="暂无记账记录" mode="list"></u-empty>
			<text class="empty-message">点击下方按钮添加第一条记账记录</text>
		</view>

		<!-- 底部操作栏 -->
		<view class="footer-container">
			<view class="footer-content">
				<view class="footer-summary">
					<text class="summary-text">总计: </text>
					<text class="summary-amount">¥{{ formatCurrency(totalAmount) }}</text>
				</view>
				<view class="footer-actions">
					<navigator class="expense-button" url="/pageNew/pages/accounting/add-expense">
						<u-icon name="minus-circle" color="#ffffff" size="18" class="footer-icon"></u-icon>
						<text>支出</text>
					</navigator>
					<navigator class="income-button" url="/pageNew/pages/accounting/add-income">
						<u-icon name="plus-circle" color="#ffffff" size="18" class="footer-icon"></u-icon>
						<text>收入</text>
					</navigator>
				</view>
			</view>
		</view>

		<!-- 删除确认弹窗 -->
		<view class="delete-modal" v-if="showDeleteModal">
			<view class="modal-content">
				<view class="modal-header">
					<text class="modal-title">确认删除</text>
				</view>
				<view class="modal-body">
					<text class="modal-message">您确定要删除这条记账记录吗？此操作不可撤销。</text>
					<view class="modal-actions">
						<view class="cancel-button" @click="toggleDeleteModal">取消</view>
						<view class="confirm-button" @click="confirmDeleteRecord">删除</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				// 公司信息和ID
				companyInfo: uni.getStorageSync('companyInfo'),
				http: uni.$u.http,
				// 支出分类数据
				expenseCategoriesList: [],
				showAllCategories: false,
				compareWithLastMonth: false,
				displayedCategories: [],

				// 记账记录数据
				accountingRecords: [],

				// 筛选面板控制
				showFilterPanel: false,

				// 日期筛选
				startDate: '',
				endDate: '',

				// 记录类型筛选数据
				recordTypes: [{
						value: 'all',
						label: '全部'
					},
					{
						value: 'income',
						label: '收入'
					},
					{
						value: 'expense',
						label: '支出'
					}
				],
				selectedRecordType: 0,

				// 布尔类型筛选选项
				booleanOptions: [{
						value: 'all',
						label: '全部'
					},
					{
						value: 'true',
						label: '是'
					},
					{
						value: 'false',
						label: '否'
					}
				],

				// 布尔筛选绑定值（0=全部，1=是，2=否）
				selectedHasInvoice: 0,
				selectedHasBankFlow: 0,
				selectedHasVoucher: 0,
				selectedHasAttachment: 0,

				// 收入类型筛选数据
				incomeCategories: [{
						value: 'all',
						label: '全部'
					}
					// 会从接口获取
				],
				selectedIncomeCategory: 0,

				// 支出类型筛选数据
				expenseCategories: [{
						value: 'all',
						label: '全部'
					}
					// 会从接口获取
				],
				selectedExpenseCategory: 0,

				// 统计数据
				totalIncome: 0,
				totalExpense: 0,
				totalAmount: 0,

				// 删除确认弹窗
				showDeleteModal: false,
				deleteRecordId: ''
			};
		},
		computed: {
			companyId() {
				return this.companyInfo.id || '';
			}
		},
		watch: {
			// 监听分类展开状态变化
			showAllCategories(val) {
				this.updateDisplayedCategories();
			}
		},
		onLoad() {
			// 页面加载时初始化
			this.initDateRange();
			this.loadCategoryData();
			this.loadAccountingRecords();
		},
		onShow() {
			// 页面显示时重新加载数据
			this.loadAccountingRecords();
		},
		methods: {
			/**
			 * 获取公司ID
			 */
			getCompanyId() {
				return this.companyInfo ? this.companyInfo.id : '';
			},

			/**
			 * 更新显示的支出分类
			 */
			updateDisplayedCategories() {
				if (this.showAllCategories) {
					this.displayedCategories = [...this.expenseCategoriesList];
				} else {
					this.displayedCategories = this.expenseCategoriesList.slice(0, 3);
				}
			},

			/**
			 * 切换分类展开/收起状态
			 */
			toggleExpandAll() {
				this.showAllCategories = !this.showAllCategories;
			},

			/**
			 * 格式化日期为 yyyy-mm-dd 格式
			 * @param {Date} date - 日期对象
			 * @returns {string} 格式化后的日期字符串
			 */
			formatDate(date) {
				if (!date) return '';
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				return `${year}-${month}-${day}`;
			},

			/**
			 * 格式化金额为带千分位的两位小数
			 * @param {number} amount - 金额数值
			 * @returns {string} 格式化后的金额字符串
			 */
			formatCurrency(amount) {
				if (!amount) return '0.00';
				return amount.toFixed(2).replace(/\d(?=(\d{3})+\.)/g, '$&,');
			},

			/**
			 * 切换筛选面板显示/隐藏
			 */
			toggleFilterPanel() {
				this.showFilterPanel = !this.showFilterPanel;
			},

			/**
			 * 初始化日期范围为最近一个月
			 */
			initDateRange() {
				const endDate = new Date();
				const startDate = new Date();
				startDate.setMonth(startDate.getMonth() - 1);
				this.startDate = this.formatDate(startDate);
				this.endDate = this.formatDate(endDate);
			},

			/**
			 * 开始日期变更处理
			 * @param {Object} e - 事件对象
			 */
			onStartDateChange(e) {
				this.startDate = e.detail.value;
			},

			/**
			 * 结束日期变更处理
			 * @param {Object} e - 事件对象
			 */
			onEndDateChange(e) {
				this.endDate = e.detail.value;
			},

			/**
			 * 记录类型变更处理
			 * @param {Object} e - 事件对象
			 */
			onRecordTypeChange(e) {
				this.selectedRecordType = e.detail.value;
			},

			/**
			 * 收入类型变更处理
			 * @param {Object} e - 事件对象
			 */
			onIncomeCategoryChange(e) {
				this.selectedIncomeCategory = e.detail.value;
			},

			/**
			 * 支出类型变更处理
			 * @param {Object} e - 事件对象
			 */
			onExpenseCategoryChange(e) {
				this.selectedExpenseCategory = e.detail.value;
			},

			/**
			 * 布尔类型单选按钮变更处理
			 * @param {string} type - 筛选类型
			 * @param {number} value - 选中值（0=全部，1=是，2=否）
			 */
			handleBooleanChange(type, value) {
				switch (type) {
					case 'hasInvoice':
						this.selectedHasInvoice = value;
						break;
					case 'hasBankFlow':
						this.selectedHasBankFlow = value;
						break;
					case 'hasVoucher':
						this.selectedHasVoucher = value;
						break;
					case 'hasAttachment':
						this.selectedHasAttachment = value;
						break;
				}
			},

			/**
			 * 重置所有筛选条件
			 */
			resetFilter() {
				this.initDateRange();
				this.selectedRecordType = 0;
				this.selectedIncomeCategory = 0;
				this.selectedExpenseCategory = 0;
				// 重置所有u-radio-group的选中状态为"全部"（0）
				this.selectedHasInvoice = 0;
				this.selectedHasBankFlow = 0;
				this.selectedHasVoucher = 0;
				this.selectedHasAttachment = 0;
			},

			/**
			 * 应用筛选条件并更新列表
			 */
			applyFilter() {
				this.showFilterPanel = false;
				this.loadAccountingRecords();
			},

			/**
			 * 加载分类数据 - 核心修复：根据后端返回的categoryType修正判断逻辑
			 */
			async loadCategoryData() {
				try {
					console.log('加载分类数据，公司ID：', this.companyId);
					// 获取记账分类列表
					const res = await this.http.get('/VipAccountingCategory/list', {
						params: {
							companyId: this.companyId,
							pageSize: 100
						}
					});

					console.log('分类接口返回数据：', res);

					// 后端返回格式：res.data.data 才是真正的列表数据
					const categoryList = res.data && res.data.data ? res.data.data : [];

					if (res.code === 200 && categoryList.length > 0) {
						// 区分收入和支出分类 - 关键修复：后端categoryType=0是收入，1是支出
						const incomeCats = [];
						const expenseCats = [];

						categoryList.forEach(cat => {
							console.log('分类项：', cat);
							// 后端返回：categoryType=0 收入类型，categoryType=1 支出类型
							if (cat.categoryType === 0) {
								incomeCats.push({
									value: cat.id,
									label: cat.categoryName
								});
							} else if (cat.categoryType === 1) {
								expenseCats.push({
									value: cat.id,
									label: cat.categoryName
								});

								// 同时添加到支出分类列表
								this.expenseCategoriesList.push({
									categoryId: cat.id,
									categoryName: cat.categoryName,
									percentage: '0%', // 后续会根据实际数据计算
									amount: '¥0.00'
								});
							}
						});

						// 更新收入和支出分类选择器数据
						this.incomeCategories = [{
							value: 'all',
							label: '全部'
						}, ...incomeCats];
						this.expenseCategories = [{
							value: 'all',
							label: '全部'
						}, ...expenseCats];

						console.log('收入分类：', this.incomeCategories);
						console.log('支出分类：', this.expenseCategories);
						console.log('支出分类列表：', this.expenseCategoriesList);

						this.updateDisplayedCategories();
						/* uni.showToast({
							title: `加载成功${categoryList.length}个分类`,
							icon: 'none'
						}); */
					} else {
						console.log('未获取到分类数据或接口返回异常');
						uni.showToast({
							title: '未获取到分类数据',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('加载分类数据失败:', error);
					uni.showToast({
						title: '加载分类失败',
						icon: 'none'
					});
				}
			},

			/**
			 * 加载并筛选记账记录 - 优化接口数据处理
			 */
			async loadAccountingRecords() {
				try {
					console.log('加载记账记录，筛选条件：', {
						companyId: this.companyId,
						startDate: this.startDate,
						endDate: this.endDate,
						recordType: this.selectedRecordType !== 0 ?
							(this.recordTypes[this.selectedRecordType].value === 'income' ? 0 : 1) : '',
						categoryId: this.selectedIncomeCategory !== 0 ?
							this.incomeCategories[this.selectedIncomeCategory].value : (this
								.selectedExpenseCategory !== 0 ? this.expenseCategories[this
									.selectedExpenseCategory].value : '')
					});

					// 构建查询参数
					const params = {
						companyId: this.companyId,
						pageSize: 100,
						startDate: this.startDate,
						endDate: this.endDate
					};

					// 添加记录类型筛选 - 关键修复：后端recordType应该和categoryType对应（0=收入，1=支出）
					if (this.selectedRecordType !== 0) {
						params.recordType = this.recordTypes[this.selectedRecordType].value === 'income' ? 0 : 1;
					}

					// 添加收入类型筛选
					if (this.selectedIncomeCategory !== 0) {
						params.categoryId = this.incomeCategories[this.selectedIncomeCategory].value;
					}

					// 添加支出类型筛选
					if (this.selectedExpenseCategory !== 0 && this.selectedRecordType === 2) {
						params.categoryId = this.expenseCategories[this.selectedExpenseCategory].value;
					}

					// 添加布尔类型筛选
					if (this.selectedHasInvoice !== 0) {
						params.hasInvoice = this.selectedHasInvoice === 1 ? 1 : 0;
					}
					if (this.selectedHasBankFlow !== 0) {
						params.hasBankFlow = this.selectedHasBankFlow === 1 ? 1 : 0;
					}
					if (this.selectedHasVoucher !== 0) {
						params.hasVoucher = this.selectedHasVoucher === 1 ? 1 : 0;
					}
					if (this.selectedHasAttachment !== 0) {
						params.hasAttachment = this.selectedHasAttachment === 1 ? 1 : 0;
					}

					// 调用接口获取记账记录
					const res = await this.http.get('/VipAccountingRecord/list', {
						params: params
					});

					console.log('记账记录接口返回：', res);

					// 处理接口返回数据格式
					const recordList = res.data && res.data.data ? res.data.data : [];

					if (res.code === 200) {
						// 转换数据格式适配前端展示
						this.accountingRecords = recordList.map(record => {
							// 查找分类名称
							let categoryLabel = '未知分类';
							if (record.categoryId) {
								const allCats = [...this.incomeCategories, ...this.expenseCategories];
								const foundCat = allCats.find(cat => cat.value == record.categoryId);
								if (foundCat) {
									categoryLabel = foundCat.label;
								}
							}

							return {
								id: record.id,
								type: record.recordType === 0 ? 'income' : 'expense', // 对应后端0=收入，1=支出
								category: record.categoryId,
								categoryLabel: categoryLabel,
								amount: record.amount || 0,
								date: this.formatDate(record.recordDate ? new Date(record.recordDate) :
									new Date()),
								remarks: record.remark || '',
								hasInvoice: record.hasInvoice === 1,
								hasBankFlow: record.hasBankFlow === 1,
								bankSerial: record.bankSerial || '',
								hasVoucher: record.hasVoucher === 1,
								hasAttachment: record.hasAttachment === 1
							};
						});

						console.log('转换后的记账记录：', this.accountingRecords);

						// 计算统计数据
						this.calculateTotals();
						// 更新支出分类统计
						this.updateCategoryStatistics();

						if (this.accountingRecords.length === 0) {
							uni.showToast({
								title: '当前筛选条件下无记账记录',
								icon: 'none'
							});
						}
					} else {
						this.accountingRecords = [];
						this.totalIncome = 0;
						this.totalExpense = 0;
						this.totalAmount = 0;
						uni.showToast({
							title: res.msg || '获取记账记录失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('加载记账记录失败:', error);
					this.accountingRecords = [];
					this.totalIncome = 0;
					this.totalExpense = 0;
					this.totalAmount = 0;
					uni.showToast({
						title: '加载记录失败',
						icon: 'none'
					});
				}
			},

			/**
			 * 计算总收入、总支出和总计
			 */
			/* calculateTotals() {
				this.totalIncome = this.accountingRecords
					.filter(record => record.type === 'income')
					.reduce((sum, record) => sum + record.amount, 0);

				this.totalExpense = this.accountingRecords
					.filter(record => record.type === 'expense')
					.reduce((sum, record) => sum + record.amount, 0);

				this.totalAmount = this.totalIncome - this.totalExpense;

				console.log('统计数据：', {
					totalIncome: this.totalIncome,
					totalExpense: this.totalExpense,
					totalAmount: this.totalAmount
				});
			},
 */
			calculateTotals() {
				this.totalIncome = this.accountingRecords
					.filter(record => record.type === 'income')
					.reduce((sum, record) => sum + Number(record.amount) || 0, 0);

				// 关键修复：支出金额取绝对值累加，确保总支出是正数
				this.totalExpense = this.accountingRecords
					.filter(record => record.type === 'expense')
					.reduce((sum, record) => sum + Math.abs(Number(record.amount) || 0), 0);

				this.totalAmount = this.totalIncome - this.totalExpense;

				console.log('统计数据（修复后）：', {
					totalIncome: this.totalIncome,
					totalExpense: this.totalExpense, // 现在是正数，如 11280
					totalAmount: this.totalAmount
				});
			},
			/**
			 * 更新支出分类统计数据
			 */
			/* updateCategoryStatistics() {
				if (!this.expenseCategoriesList.length) return;

				console.log('更新支出分类统计，总支出：', this.totalExpense);
				console.log('支出分类列表：', this.expenseCategoriesList);

				// 计算每个分类的总金额
				const categoryTotals = {};

				// 初始化所有分类的金额为0
				this.expenseCategoriesList.forEach(cat => {
					categoryTotals[cat.categoryId] = 0;
				});

				// 累加每个分类的支出金额
				this.accountingRecords
					.filter(record => record.type === 'expense' && record.category)
					.forEach(record => {
						if (categoryTotals.hasOwnProperty(record.category)) {
							categoryTotals[record.category] += record.amount;
							console.log(
								`分类${record.categoryLabel}增加金额：${record.amount}，累计：${categoryTotals[record.category]}`
							);
						}
					});

				// 更新分类统计数据
				this.expenseCategoriesList.forEach(cat => {
					const total = categoryTotals[cat.categoryId] || 0;
					cat.amount = `¥${this.formatCurrency(total)}`;
					// 计算占比
					cat.percentage = this.totalExpense > 0 ?
						`${Math.round((total / this.totalExpense) * 100)}%` :
						'0%';
				});

				// 按金额排序
				this.expenseCategoriesList.sort((a, b) => {
					const amountA = parseFloat(a.amount.replace(/[^\d.-]/g, ''));
					const amountB = parseFloat(b.amount.replace(/[^\d.-]/g, ''));
					return amountB - amountA;
				});

				this.updateDisplayedCategories();
				console.log('更新后的支出分类统计：', this.expenseCategoriesList);
			}, */
			updateCategoryStatistics() {
				if (!this.expenseCategoriesList.length) return;

				console.log('更新支出分类统计（修复后），总支出：', this.totalExpense);
				console.log('支出分类列表：', this.expenseCategoriesList);

				const categoryTotals = {};
				// 初始化分类金额为0
				this.expenseCategoriesList.forEach(cat => {
					categoryTotals[cat.categoryId] = 0;
				});

				// 关键修复：支出金额取绝对值累加，确保分类金额是正数
				this.accountingRecords
					.filter(record => record.type === 'expense' && record.category)
					.forEach(record => {
						const categoryKey = String(record.category); // 统一类型，避免匹配失败
						if (categoryTotals.hasOwnProperty(categoryKey)) {
							// 取绝对值累加，避免负数影响
							categoryTotals[categoryKey] += Math.abs(Number(record.amount) || 0);
							console.log(
								`分类${record.categoryLabel}增加金额：${Math.abs(record.amount)}，累计：${categoryTotals[categoryKey]}`
							);
						}
					});

				// 更新分类金额和占比
				this.expenseCategoriesList.forEach(cat => {
					const total = categoryTotals[cat.categoryId] || 0;
					// 分类金额显示正数（已通过绝对值处理）
					cat.amount = `¥${this.formatCurrency(total)}`;
					// 占比计算（此时totalExpense是正数，可正常计算）
					cat.percentage = this.totalExpense > 0 ?
						`${Math.round((total / this.totalExpense) * 100)}%` :
						'0%';
				});

				// 按金额排序（正数排序正常）
				this.expenseCategoriesList.sort((a, b) => {
					const amountA = parseFloat(a.amount.replace(/[^\d.-]/g, '')) || 0;
					const amountB = parseFloat(b.amount.replace(/[^\d.-]/g, '')) || 0;
					return amountB - amountA;
				});

				this.updateDisplayedCategories();
				console.log('更新后的支出分类统计（修复后）：', this.expenseCategoriesList);
			},

			/**
			 * 显示删除确认弹窗
			 * @param {string} id - 要删除的记录ID
			 */
			confirmDelete(id) {
				this.deleteRecordId = id;
				this.showDeleteModal = true;
			},

			/**
			 * 切换删除确认弹窗显示状态
			 */
			toggleDeleteModal() {
				this.showDeleteModal = !this.showDeleteModal;
			},

			/**
			 * 确认删除记录
			 */
			async confirmDeleteRecord() {
				try {
					const res = await this.http.delete(`/VipAccountingRecord/${this.deleteRecordId}`);

					if (res.success || res.code === 200) {
						uni.showToast({
							title: '删除成功',
							icon: 'success'
						});
						// 重新加载列表
						this.loadAccountingRecords();
					} else {
						uni.showToast({
							title: res.msg || '删除失败',
							icon: 'none'
						});
					}
				} catch (error) {
					console.error('删除记录失败:', error);
					uni.showToast({
						title: '删除失败',
						icon: 'none'
					});
				} finally {
					// 关闭弹窗
					this.toggleDeleteModal();
				}
			}
		}
	};
</script>

<style>
	.accounting-container {
		min-height: 100vh;
		background-color: #f9fafb;
		padding-bottom: 80px;
	}

	/* 支出分类样式 */
	.expense-category-container {
		background-color: #ffffff;
		border-radius: 8px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		margin: 16px;
		padding: 16px;
	}

	.category-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 16px;
	}

	.category-title {
		font-size: 16px;
		font-weight: 600;
		color: #333;
	}

	.category-actions {
		display: flex;
		align-items: center;
	}

	.compare-text {
		font-size: 14px;
		color: #666;
		margin-right: 8px;
	}

	.category-list {
		max-height: 200px;
		overflow: hidden;
		transition: max-height 0.3s ease;
	}

	.category-item {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 10px 0;
		border-bottom: 1px solid #f3f4f6;
	}

	.category-item:last-child {
		border-bottom: none;
	}

	.category-info {
		display: flex;
		align-items: center;
	}

	.category-rank {
		color: #999;
		margin-right: 8px;
	}

	.category-name {
		font-size: 14px;
		color: #333;
		min-width: 120px;
	}

	.category-percentage {
		font-size: 14px;
		color: #666;
		margin-left: 16px;
	}

	.category-amount {
		font-size: 14px;
		font-weight: 500;
		color: #333;
	}

	.expand-all {
		display: flex;
		align-items: center;
		justify-content: center;
		color: #1e88e5;
		font-size: 14px;
		margin-top: 12px;
		cursor: pointer;
	}

	/* 筛选按钮容器 */
	.filter-button-container {
		padding: 20rpx 30rpx;
		background-color: #fff;
		border-bottom: 1px solid #eee;
		display: flex;
		padding: 20rpx;
		justify-content: flex-end;
	}

	.filter-button {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		padding: 10rpx;
		align-items: center;
		justify-content: center;
		border-radius: 50%;
		background-color: #f0f7f0;
		margin-left: auto;
	}

	/* 筛选面板样式 */
	.filter-panel {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		top: auto;
		background-color: #ffffff;
		box-shadow: 0 -2px 12px rgba(0, 0, 0, 0.1);
		z-index: 99;

		border-radius: 20rpx 20rpx 0 0;
		padding: 30rpx;
		padding-top: 110rpx;
		box-sizing: border-box;
	}

	.panel {
		max-height: 70vh;
		overflow-y: auto;
	}

	/* 固定顶部按钮区域 */
	.filter-actions-top {
		position: absolute;
		top: 30rpx;
		left: 30rpx;
		right: 30rpx;
		display: flex;
		justify-content: space-between;
		align-items: center;
		background-color: #ffffff;
		z-index: 101;
		padding: 15rpx 0;
		margin: 0;
	}

	/* 三个按钮样式 */
	.filter-actions-top .cancel-button,
	.filter-actions-top .reset-button,
	.filter-actions-top .apply-button {
		font-size: 28rpx;
		padding: 8rpx 20rpx;
		border-radius: 8rpx;
	}

	.filter-actions-top .cancel-button {
		color: #666;
	}

	.filter-actions-top .reset-button {
		color: #1e88e5;
		background-color: #f0f8ff;
	}

	.filter-actions-top .apply-button {
		color: #ffffff;
		background-color: #1e88e5;
		font-weight: 500;
	}

	/* 筛选内容区域 */
	.filter-content {
		width: 100%;
	}

	/* 筛选区域样式 */
	.filter-section {
		margin-bottom: 35rpx;
	}

	.filter-label {
		display: block;
		font-size: 28rpx;
		color: #666;
		margin-bottom: 15rpx;
	}

	/* 日期选择器样式 */
	.date-range-picker {
		display: flex;
		align-items: center;
		gap: 12rpx;
	}

	.date-picker {
		flex: 1;
		padding: 18rpx 20rpx;
		border: 1px solid #d9d9d9;
		border-radius: 10rpx;
		font-size: 26rpx;
	}

	.date-separator {
		color: #8c8c8c;
		font-size: 26rpx;
	}

	/* 下拉选择器样式 */
	.type-picker,
	.income-picker,
	.expense-picker {
		width: 100%;
		padding: 18rpx 20rpx;
		border: 1px solid #d9d9d9;
		border-radius: 10rpx;
		font-size: 26rpx;
		box-sizing: border-box;
	}

	/* u-radio-group 样式 */
	.boolean-filter {
		margin-bottom: 35rpx;
	}

	.u-radio-group {
		width: 100%;
		display: flex;
		gap: 15rpx;
	}

	.u-radio {
		flex: 1;
		height: 70rpx;
		line-height: 70rpx;
		font-size: 26rpx;
		color: #666;
		background: transparent;
	}

	.u-radio-checked {
		color: #1e88e5 !important;
		font-weight: 500;
	}

	.u-radio__icon {
		display: none !important;
	}

	/* 统计卡片样式 */
	.stats-container {
		display: grid;
		grid-template-columns: 1fr 1fr;
		gap: 16px;
		margin: 16px;
		margin-top: 12rpx;
	}

	.stat-card {
		background-color: #ffffff;
		border-radius: 8px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		padding: 16px;
	}

	.income-card {
		border-left: 4px solid #10B981;
	}

	.expense-card {
		border-left: 4px solid #EF4444;
	}

	.stat-label {
		display: block;
		font-size: 14px;
		color: #6b7280;
		margin-bottom: 4px;
	}

	.stat-value {
		font-size: 20px;
		font-weight: 600;
	}

	/* 记录列表样式 */
	.records-container {
		margin: 16px;
	}

	.records-header {
		padding: 16px;
		border-bottom: 1px solid #e5e7eb;
	}

	.records-title {
		font-size: 16px;
		font-weight: 600;
	}

	.records-list {
		display: flex;
		flex-direction: column;
		gap: 12px;
	}

	.record-card {
		display: flex;
		align-items: flex-start;
		background-color: #ffffff;
		border-radius: 8px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
		padding: 16px;
	}

	.record-icon {
		width: 40px;
		height: 40px;
		border-radius: 50%;
		display: flex;
		align-items: center;
		justify-content: center;
		margin-right: 12px;
		margin-top: 4px;
	}

	.income-icon {
		background-color: #e6f7ee;
	}

	.expense-icon {
		background-color: #fee2e2;
	}

	.record-details {
		flex: 1;
	}

	.record-category {
		display: block;
		font-size: 16px;
		font-weight: 500;
	}

	.record-date {
		display: block;
		font-size: 12px;
		color: #6b7280;
		margin-bottom: 8px;
	}

	.record-additional-info {
		display: flex;
		flex-wrap: wrap;
		gap: 12px;
	}

	.info-item {
		display: flex;
		align-items: center;
		font-size: 12px;
	}

	.info-label {
		color: #999;
	}

	.info-value {
		color: #666;
	}

	.record-actions-row {
		display: flex;
		justify-content: flex-end;
		margin-top: 8px;
	}

	.record-actions {
		display: flex;
		gap: 12px;
	}

	.edit-button,
	.delete-button {
		width: 36px;
		height: 36px;
		display: flex;
		align-items: center;
		justify-content: center;
	}

	.edit-button:hover,
	.delete-button:hover {
		background-color: #e5e7eb;
		border-radius: 50%;
	}

	.record-amount {
		font-size: 16px;
		font-weight: 600;
		white-space: nowrap;
		align-self: flex-end;
		margin-left: 12px;
	}

	.income-amount {
		color: #10B981;
	}

	.expense-amount {
		color: #EF4444;
	}

	/* 空状态样式 */
	.empty-state {
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;
		padding: 48px 16px;
		background-color: #ffffff;
		border-radius: 8px;
		box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
		margin: 16px;
	}

	.empty-message {
		font-size: 14px;
		color: #6b7280;
		text-align: center;
	}

	/* 底部操作栏样式 */
	.footer-container {
		position: fixed;
		bottom: 0;
		left: 0;
		right: 0;
		background-color: #ffffff;
		border-top: 1px solid #e5e7eb;
		padding: 12px 16px;
		z-index: 80;
	}

	.footer-content {
		width: 100%;
		max-width: 750rpx;
		margin: 0 auto;
		display: flex;
		align-items: center;
		justify-content: space-between;
	}

	.footer-actions {
		display: flex;
		gap: 8px;
	}

	.expense-button,
	.income-button {
		padding: 8px 16px;
		border-radius: 8px;
		font-size: 14px;
		display: flex;
		align-items: center;
	}

	.footer-icon {
		margin-right: 4px;
	}

	.expense-button {
		background-color: #42A5F5;
		color: #ffffff;
	}

	.income-button {
		background-color: #1e88e5;
		color: #ffffff;
	}

	/* 删除弹窗样式 */
	.delete-modal {
		position: fixed;
		top: 0;
		left: 0;
		right: 0;
		bottom: 0;
		background-color: rgba(0, 0, 0, 0.5);
		display: flex;
		align-items: center;
		justify-content: center;
		z-index: 200;
	}

	.modal-content {
		width: 90%;
		max-width: 400px;
		background-color: #ffffff;
		border-radius: 8px;
	}

	.modal-header {
		padding: 16px;
		border-bottom: 1px solid #e5e7eb;
	}

	.modal-title {
		font-size: 16px;
		font-weight: 600;
	}

	.modal-body {
		padding: 16px;
	}

	.modal-message {
		display: block;
		font-size: 14px;
		margin-bottom: 16px;
	}

	.modal-actions {
		display: flex;
		justify-content: flex-end;
		gap: 8px;
	}

	.modal-actions .cancel-button {
		background-color: #e5e7eb;
		color: #374151;
		padding: 8px 16px;
		border-radius: 8px;
		font-size: 14px;
	}

	.modal-actions .confirm-button {
		background-color: #EF4444;
		color: #ffffff;
		padding: 8px 16px;
		border-radius: 8px;
		font-size: 14px;
	}

	/* 滚动条样式优化 */
	.panel::-webkit-scrollbar {
		width: 6px;
	}

	.panel::-webkit-scrollbar-track {
		background: #f5f5f5;
		border-radius: 3px;
	}

	.panel::-webkit-scrollbar-thumb {
		background: #d9d9d9;
		border-radius: 3px;
	}

	.panel::-webkit-scrollbar-thumb:hover {
		background: #bfbfbf;
	}
</style>